<template>
  <div class="video-browser">
    <div class="video-browser-header">
      <el-switch
        v-model="showGeneratedVideos"
        active-text="生成视频"
        inactive-text="原始视频"
        @change="handleToggleVideoType"
      />
    </div>
    
    <el-scrollbar 
    height="calc(80vh - 80px)"
    >
    <div class="video-grid">
        <video-card
        v-for="(path, index) in currentVideos"
        :key="`${path}-${videoRefreshKey}-${index}`"
        :videoUrl="addNoCacheParam(path)"
        class="video-item"
        />
      </div>
      
      <div v-if="currentVideos.length === 0" class="no-videos">
        <el-empty description="暂无可以预览的视频" />
      </div>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { defineProps, defineEmits, computed, ref } from 'vue';
import VideoCard from '@/components/VideoCard.vue';

const props = defineProps({
  videoPaths: {
    type: Array,
    required: true,
    default: () => []
  },
  generatedVideoPaths: {
    type: Array,
    default: () => []
  },
  defaultShowGenerated: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['toggle-video-type']);
const showGeneratedVideos = ref(props.defaultShowGenerated);
const videoRefreshKey = ref(Date.now()); // 用于刷新视频的key

// 根据切换状态显示不同的视频列表
const currentVideos = computed(() => {
  return showGeneratedVideos.value ? props.generatedVideoPaths : props.videoPaths;
});

// 添加时间戳参数以防止缓存
const addNoCacheParam = (url) => {
  if (!url) return '';
  
  const separator = url.includes('?') ? '&' : '?';
  return `${url}${separator}t=${videoRefreshKey.value}`;
};

const handleToggleVideoType = () => {
  // 切换视频类型时更新刷新键，确保视频重新加载
  videoRefreshKey.value = Date.now();
  emit('toggle-video-type', showGeneratedVideos.value);
};

// 提供方法让父组件可以控制视图状态
defineExpose({
  setShowGeneratedVideos(value) {
    showGeneratedVideos.value = value;
    // 强制刷新视频
    videoRefreshKey.value = Date.now();
  },
  
  // 添加一个方法，允许父组件手动刷新视频
  refreshVideos() {
    videoRefreshKey.value = Date.now();
  }
});
</script>
<style scoped>
.video-browser {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.video-browser-header {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 16px;
}

.video-scrollbar {
  flex-grow: 0;
}

.video-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  padding: 8px;
}

.video-card {
  transition: all 0.3s ease;
  border-radius: 8px;
  overflow: hidden;
}

.video-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
}

.video-item {
  width: 100%;
}

.no-videos {
  padding: 30px;
  text-align: center;
  color: #909399;
  font-size: 14px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  margin: 20px;
}
</style>